import sys
import os
import requests
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QMainWindow, QButtonGroup, QAction, QLabel, QHBoxLayout, QRadioButton, QWidget, QSlider, \
    QVBoxLayout, QPushButton, QTextEdit, QStatusBar, QApplication, QMessageBox, QFileDialog, QComboBox, QDialog
from GoogleFreeTrans import Translator

headers = {
    "user-agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36",
}

son_list= {
    '554':'akari/',
    '1206':'yukari/',
    '1208':'seika/',
    '1205':'maki/',
    '1202':'zunko/',
    '1209':'kiritan/',
    '552':'akane/',
    '551':'aoi/',
    '2006':'una/'

}

class Tran():
    def __init__(self):
        self.transfer_en=None
        self.transfer_cn=None

        self.make_trans_cn()
        self.make_trans_en()
        #self.cn_to_ja('你好。')

    def make_trans_cn(self):
        try:
            self.transfer_cn = Translator.translator(src='zh-CN', dest='ja')
        except AttributeError:
            # print('rebulid')
            self.make_trans_cn()

    def make_trans_en(self):
        try:
            self.transfer_en=Translator.translator(src='en', dest='ja')
        except AttributeError:
            #print('rebulid')
            self.make_trans_en()

    def cn_to_ja(self,text):
        # print(self.transfer_cn.translate(text))
        return self.transfer_cn.translate(text)

    def en_to_ja(self,text):
        return self.transfer_en.translate(text)
        # print(self.transfer_en.translate(text))

class ComboxColor(QWidget):
    def __init__(self, parents=None):
        super(ComboxColor, self).__init__(parents)
        self.setWindowTitle('ComboxColor')
        self.resize(300, 90)
        layout = QVBoxLayout()
        self.lbl = QLabel('red')

        self.cb = QComboBox()
        self.cb.addItem('red')
        self.cb.addItems(['blue', 'green', 'yellow'])
        self.cb.currentIndexChanged.connect(self.schange_color)
        layout.addWidget(self.cb)
        layout.addWidget(self.lbl)
        self.selected_color='red'
        self.setLayout(layout)

    def schange_color(self, i):
        self.lbl.setText(self.cb.currentText())
        self.selected_color=self.cb.currentText()
        # print('Items are:')
        # for count in range(self.cb.count()):
        #     print('item' + str(count) + '=' + self.cb.itemText(count))
        #     print('Current index', i, 'changed', self.cb.currentText())
    def __del__(self):
        print(self.selected_color)
        return self.selected_color

class Vro3(QMainWindow):
    def __init__(self, parents=None):
        super(Vro3, self).__init__(parents)
        self.setWindowTitle('Vro3')

        self.super_parameter = {
            'speed': 10,
            'pitch': 10,
            'range': 10,
            'anger': 10,
            'sadness': 10,
            'joy': 10,
            'file_path':'C:/vro3Out/',
            'selected':1206,
            'ext':'ogg'
        }
        self.transfer=Tran()

        vros_group = QButtonGroup(self)

        bar = self.menuBar()
        about = bar.addMenu('About')
        setting = bar.addMenu('Setting')

        author = QAction('Author', self)
        quit = QAction('Quit', self)
        about.addAction(author)
        about.addAction(quit)
        about.triggered[QAction].connect(self.processtrigger)
        # about menu block

        se = QAction('Set', self)
        setting.addAction(se)
        setting.triggered[QAction].connect(self.processtrigger)


        label_akane = QLabel(self)
        label_aoi = QLabel(self)
        label_akane.setPixmap(QPixmap('../head/6.png'))
        label_aoi.setPixmap(QPixmap('../head/1.png'))

        kotonoha_imgs = QHBoxLayout()
        kotonoha_imgs.addWidget(label_akane)
        kotonoha_imgs.addWidget(label_aoi)

        radio_akane=QRadioButton('茜',self)
        radio_aoi=QRadioButton('葵',self)
        vros_group.addButton(radio_akane)
        vros_group.addButton(radio_aoi)

        radio_akane.toggled.connect(lambda: self.select_vro(552))
        radio_aoi.toggled.connect(lambda: self.select_vro(551))

        radio_vro2=QHBoxLayout()
        radio_vro2.addWidget(radio_akane)
        radio_vro2.addWidget(radio_aoi)
        radio_vro2_widget=QWidget()
        radio_vro2_widget.setLayout(radio_vro2)




        # next is vro2 attr anger
        self.anger_sl = QSlider(Qt.Vertical)
        self.anger_sl.setMinimum(0)
        self.anger_sl.setMaximum(10)
        self.anger_sl.setSingleStep(1)
        self.anger_sl.setValue(0)
        self.anger_sl.valueChanged.connect(self.change_anger_value)
        self.anger_label = QLabel('anger:0.0')
        anger_select_layout = QVBoxLayout()
        anger_select_layout.addWidget(self.anger_sl)
        anger_select_layout.addWidget(self.anger_label)
        anger_select_layout_widget = QWidget()
        anger_select_layout_widget.setLayout(anger_select_layout)

        # next is vro2 attr sadness
        self.sadness_sl = QSlider(Qt.Vertical)
        self.sadness_sl.setMinimum(0)
        self.sadness_sl.setMaximum(10)
        self.sadness_sl.setSingleStep(1)
        self.sadness_sl.setValue(0)
        self.sadness_sl.valueChanged.connect(self.change_sadness_value)
        self.sadness_label = QLabel('sad:0.0')
        sadness_select_layout = QVBoxLayout()
        sadness_select_layout.addWidget(self.sadness_sl)
        sadness_select_layout.addWidget(self.sadness_label)
        sadness_select_layout_widget = QWidget()
        sadness_select_layout_widget.setLayout(sadness_select_layout)

        # next is vro2 attr joy
        self.joy_sl = QSlider(Qt.Vertical)
        self.joy_sl.setMinimum(0)
        self.joy_sl.setMaximum(10)
        self.joy_sl.setSingleStep(1)
        self.joy_sl.setValue(0)
        self.joy_sl.valueChanged.connect(self.change_joy_value)
        self.joy_label = QLabel('joy:0.0')
        joy_select_layout = QVBoxLayout()
        joy_select_layout.addWidget(self.joy_sl)
        joy_select_layout.addWidget(self.joy_label)
        joy_select_layout_widget = QWidget()
        joy_select_layout_widget.setLayout(joy_select_layout)

        # vro2 attrs group
        vro2_attr_layout = QHBoxLayout()

        vro2_attr_layout.addWidget(anger_select_layout_widget)
        vro2_attr_layout.addWidget(sadness_select_layout_widget)
        vro2_attr_layout.addWidget(joy_select_layout_widget)
        vro2_attr_layout_widget=QWidget()
        vro2_attr_layout_widget.setLayout(vro2_attr_layout)


        kotonoha_imgs_widgt=QWidget()
        kotonoha_imgs_widgt.setLayout(kotonoha_imgs)

        vro2_imgs_and_sliders=QVBoxLayout()
        vro2_imgs_and_sliders.addWidget(kotonoha_imgs_widgt)
        vro2_imgs_and_sliders.addWidget(radio_vro2_widget)
        vro2_imgs_and_sliders.addWidget(vro2_attr_layout_widget)
        vro2_imgs_and_sliders_widget=QWidget()
        vro2_imgs_and_sliders_widget.setLayout(vro2_imgs_and_sliders)

        # add vro imgs
        label_yukari = QLabel(self)
        label_zunko = QLabel(self)
        label_seika = QLabel(self)
        label_kiritan = QLabel(self)
        label_maki = QLabel(self)
        label_akari = QLabel(self)
        label_una=QLabel(self)
        # add labels

        label_yukari.setPixmap(QPixmap('../head/2.png'))
        #label_yukari.setSizePolicy(16, 16)
        label_zunko.setPixmap(QPixmap('../head/3.png'))
        label_seika.setPixmap(QPixmap('../head/4.png'))
        label_kiritan.setPixmap(QPixmap('../head/5.png'))
        label_maki.setPixmap(QPixmap('../head/7.png'))
        label_akari.setPixmap(QPixmap('../head/8.png'))
        label_una.setPixmap(QPixmap('../head/10.jpg'))
        # add images

        images2 = QHBoxLayout()
        images2.addWidget(label_yukari)
        images2.addStretch()
        images2.addWidget(label_zunko)
        images2.addStretch()
        images2.addWidget(label_seika)
        images2.addStretch()
        images2.addWidget(label_kiritan)
        images2.addStretch()
        images2.addWidget(label_maki)
        images2.addStretch()
        images2.addWidget(label_akari)
        images2.addStretch()
        images2.addWidget(label_una)
        images2.addStretch()
        # add images label into layout 'image2'

        images2_widget=QWidget()
        images2_widget.setLayout(images2)

        radio_yukari=QRadioButton('ゆかり',self)
        radio_zunko=QRadioButton('ずん子',self)
        radio_seika=QRadioButton('セイカ',self)
        radio_kiritan=QRadioButton('きりたん',self)
        radio_maki=QRadioButton('マキ',self)
        radio_akari=QRadioButton('あかり',self)
        radio_una=QRadioButton('ウナ',self)
        radio_yukari.setChecked(True)

        radio_yukari.toggled.connect(lambda: self.select_vro(1206))
        radio_zunko.toggled.connect(lambda: self.select_vro(1202))
        radio_seika.toggled.connect(lambda: self.select_vro(1208))
        radio_kiritan.toggled.connect(lambda: self.select_vro(1209))
        radio_maki.toggled.connect(lambda: self.select_vro(1205))
        radio_akari.toggled.connect(lambda: self.select_vro(554))
        radio_una.toggled.connect(lambda: self.select_vro(2006))

        vros_group.addButton(radio_yukari)
        vros_group.addButton(radio_zunko)
        vros_group.addButton(radio_seika)
        vros_group.addButton(radio_kiritan)
        vros_group.addButton(radio_maki)
        vros_group.addButton(radio_akari)
        vros_group.addButton(radio_una)

        radio_vro1=QHBoxLayout()
        radio_vro1.addWidget(radio_yukari)
        radio_vro1.addWidget(radio_zunko)
        radio_vro1.addWidget(radio_seika)
        radio_vro1.addWidget(radio_kiritan)
        radio_vro1.addWidget(radio_maki)
        radio_vro1.addWidget(radio_akari)
        radio_vro1.addWidget(radio_una)
        radio_vro1_widget=QWidget()
        radio_vro1_widget.setLayout(radio_vro1)




        self.speed_sl = QSlider(Qt.Horizontal)
        self.speed_sl.setMinimum(5)
        self.speed_sl.setMaximum(40)
        self.speed_sl.setSingleStep(1)
        self.speed_sl.setValue(10)
        self.speed_sl.valueChanged.connect(self.change_speed_value)
        self.pitch_sl = QSlider(Qt.Horizontal)
        self.pitch_sl.setMinimum(5)
        self.pitch_sl.setMaximum(20)
        self.pitch_sl.setSingleStep(1)
        self.pitch_sl.setValue(10)
        self.pitch_sl.valueChanged.connect(self.change_pitch_value)
        self.range_sl = QSlider(Qt.Horizontal)
        self.range_sl.setMinimum(0)
        self.range_sl.setMaximum(20)
        self.range_sl.setSingleStep(1)
        self.range_sl.setValue(10)
        self.range_sl.valueChanged.connect(self.change_range_value)

        self.speed_label = QLabel('话速:1.0')
        self.pitch_label = QLabel('音高:1.0')
        self.range_label = QLabel('抑扬:1.0')

        speed_select_layout = QHBoxLayout()
        speed_select_layout.addWidget(self.speed_sl)
        speed_select_layout.addWidget(self.speed_label)

        pitch_select_layout = QHBoxLayout()
        pitch_select_layout.addWidget(self.pitch_sl)
        pitch_select_layout.addWidget(self.pitch_label)

        range_select_layout = QHBoxLayout()
        range_select_layout.addWidget(self.range_sl)
        range_select_layout.addWidget(self.range_label)

        vro1_attr_layout = QVBoxLayout()
        speed_select_layout_widget = QWidget()
        pitch_select_layout_widget = QWidget()
        range_select_layout_widget = QWidget()
        speed_select_layout_widget.setLayout(speed_select_layout)
        pitch_select_layout_widget.setLayout(pitch_select_layout)
        range_select_layout_widget.setLayout(range_select_layout)

        vro1_attr_layout.addWidget(speed_select_layout_widget)
        vro1_attr_layout.addWidget(pitch_select_layout_widget)
        vro1_attr_layout.addWidget(range_select_layout_widget)
        vro1_attr_layout_widget=QWidget()
        vro1_attr_layout_widget.setLayout(vro1_attr_layout)



        trans_btn_en = QPushButton('en->ja')
        trans_btn_cn = QPushButton('cn->ja')

        btns = QVBoxLayout()
        btns.addWidget(trans_btn_en)
        btns.addWidget(trans_btn_cn)
        btns_widgt = QWidget()
        btns_widgt.setLayout(btns)
        # buttons in transform

        self.will_be_trans = QTextEdit()
        self.target_mess_to_read = QTextEdit()

        will_be_trans_and_trans_btns = QHBoxLayout()
        will_be_trans_and_trans_btns.addWidget(self.will_be_trans)
        will_be_trans_and_trans_btns.addWidget(btns_widgt)
        will_be_trans_and_trans_btns_widgt = QWidget()
        will_be_trans_and_trans_btns_widgt.setLayout(will_be_trans_and_trans_btns)
        main_message_panel = QVBoxLayout()
        main_message_panel.addWidget(will_be_trans_and_trans_btns_widgt)
        main_message_panel.addWidget(self.target_mess_to_read)

        trans_btn_en.clicked.connect(self.trans_en)
        trans_btn_cn.clicked.connect(self.trans_cn)
        main_message_panel_widget=QWidget()
        main_message_panel_widget.setLayout(main_message_panel)


        get_btn = QPushButton('获取')
        self.ogg_label = QRadioButton('.ogg')
        self.wav_label = QRadioButton('.wav')
        self.mp3_label = QRadioButton('.mp3')
        self.ogg_label.setChecked(True)
        self.ogg_label.toggled.connect(lambda: self.select_type('ogg'))
        self.wav_label.toggled.connect(lambda: self.select_type('wav'))
        self.mp3_label.toggled.connect(lambda: self.select_type('mp3'))

        file_name_layout = QVBoxLayout()
        file_name_layout.addWidget(self.ogg_label)
        file_name_layout.addWidget(self.mp3_label)
        file_name_layout.addWidget(self.wav_label)

        self.select_path=QPushButton()
        self.select_path.setText('保存路径')

        self.select_path.clicked.connect(self.ask_path)

        file_name_layout_widgt = QWidget()
        file_name_layout_widgt.setLayout(file_name_layout)
        get_btns_layout = QHBoxLayout()
        get_btns_layout.addWidget(file_name_layout_widgt)
        get_btns_layout.addWidget(self.select_path)
        get_btns_layout.addWidget(get_btn)
        get_btns_layout_widget=QWidget()
        get_btns_layout_widget.setLayout(get_btns_layout)

        get_btn.clicked.connect(self.get_audio)

        vro1_and_vro1_attr_and_trans=QVBoxLayout()
        vro1_and_vro1_attr_and_trans.addWidget(images2_widget)
        vro1_and_vro1_attr_and_trans.addWidget(radio_vro1_widget)
        vro1_and_vro1_attr_and_trans.addWidget(vro1_attr_layout_widget)
        vro1_and_vro1_attr_and_trans.addWidget(main_message_panel_widget)
        vro1_and_vro1_attr_and_trans.addWidget(get_btns_layout_widget)
        vro1_and_vro1_attr_and_trans_widget=QWidget()
        vro1_and_vro1_attr_and_trans_widget.setLayout(vro1_and_vro1_attr_and_trans)


        total_layout=QHBoxLayout()
        total_layout.addWidget(vro2_imgs_and_sliders_widget)
        total_layout.addWidget(vro1_and_vro1_attr_and_trans_widget)
        self.target_mess_to_read.setHtml("<font color='red'> 本ソフトは商業的に使用することは禁止です。 </font>")

        self.statusBar=QStatusBar()
        self.setStatusBar(self.statusBar)




        total_widget = QWidget()
        total_widget.setLayout(total_layout)
        self.setCentralWidget(total_widget)



    def change_speed_value(self):
        self.super_parameter['speed'] = self.speed_sl.value()
        self.speed_label.setText('话速:' + str(self.super_parameter['speed'] / 10.0))

    def change_pitch_value(self):
        self.super_parameter['pitch'] = self.pitch_sl.value()
        self.pitch_label.setText('音高:' + str(self.super_parameter['pitch'] / 10.0))

    def change_range_value(self):
        self.super_parameter['range'] = self.range_sl.value()
        self.range_label.setText('抑扬:' + str(self.super_parameter['range'] / 10.0))

    def change_anger_value(self):
        self.super_parameter['anger'] = self.anger_sl.value()
        self.anger_label.setText('anger:' + str(self.super_parameter['anger'] / 10.0))

    def change_sadness_value(self):
        self.super_parameter['sadness'] = self.sadness_sl.value()
        self.sadness_label.setText('sadness:' + str(self.super_parameter['sadness'] / 10.0))

    def change_joy_value(self):
        self.super_parameter['joy'] = self.joy_sl.value()
        self.joy_label.setText('joy:' + str(self.super_parameter['joy'] / 10.0))

    def trans_en(self):

        english_mess = self.will_be_trans.toPlainText()
        japan_mess = self.transfer.en_to_ja(english_mess)

        self.target_mess_to_read.setHtml("<font color='red'>" + japan_mess + "</font>")
        QMessageBox.information(self,'...','翻訳完了')

    def trans_cn(self):

        Chinese_mess = self.will_be_trans.toPlainText()
        japan_mess = self.transfer.cn_to_ja(Chinese_mess)

        self.target_mess_to_read.setHtml("<font color='red'>" + japan_mess + "</font>")
        QMessageBox.information(self,'...','翻訳完了')

    def get_audio(self):
        if not self.target_mess_to_read.toPlainText()=='':
            if len(self.target_mess_to_read.toPlainText())<=50:
                if not os.path.exists(self.super_parameter['file_path']):
                    os.mkdir(self.super_parameter['file_path'])

                self.statusBar.showMessage('请求发送中...')
                result=self.get_request().decode()
                tlist = result.split('\\')
                true_target = 'http://' + tlist[2][1:] + tlist[3] + tlist[4] + tlist[5][:-3]
                self.statusBar.showMessage('正在获取'+str(true_target))
                audio_save_des=self.save_audio(str(true_target))
                self.statusBar.showMessage('获取成功！'+audio_save_des)
            else:
                QMessageBox.warning(self, '!', '请勿输入过多字符')
        else:
            QMessageBox.warning(self, '!', '请输入文本')

    def select_type(self,type):
        self.super_parameter['ext']=type

        #之后的迭代中，添加每个人的目录
    def save_audio(self,path):
        audio_data = requests.get(path, headers=headers)
        audio_save_des=self.make_son_folder()+str(self.target_mess_to_read.toPlainText())+'.'+self.super_parameter['ext']
        # audio_save_des = self.make_son_folder() + str(self.target_mess_to_read.toPlainText()) + str(
        #     self.super_parameter['ext'])
        print(audio_save_des)
        with open(audio_save_des, "wb+") as temp_file:
            temp_file.write(audio_data.content)
        return audio_save_des

    def get_request(self):
        charactor_num=self.super_parameter['selected']
        # audi_para={}
        url = 'https://cloud.ai-j.jp/demo/aitalk2webapi_nop.php'
        # mess = quote(self.target_mess_to_read.toPlainText(), safe=";/?:@&=+$,", encoding="utf-8")
        mess=self.target_mess_to_read.toPlainText()
        if charactor_num in [1206,552,551]:
            audio_para = {
                'callback' : 'callback',
                'speaker_id':charactor_num,
                'text':mess,
                'ext' : self.super_parameter['ext'],
                'speed': str(self.super_parameter['speed'] / 10.0),
                'pitch': str(self.super_parameter['pitch'] / 10.0),
                'range': str(self.super_parameter['range'] / 10.0),
                'anger': str(self.super_parameter['anger'] / 10.0),
                'sadness': str(self.super_parameter['sadness'] / 10.0),
                'joy': str(self.super_parameter['joy'] / 10.0)
            }
        else:
            audio_para = {
                'callback': 'callback',
                'speaker_id':charactor_num,
                'text':mess,
                'ext': self.super_parameter['ext'],
                'speed': str(self.super_parameter['speed'] / 10.0),
                'pitch': str(self.super_parameter['pitch'] / 10.0),
                'range': str(self.super_parameter['range'] / 10.0),
            }

        result = requests.get(url=url, params=audio_para)
        requests.get(url='http://www.masaikk.xyz:10000/v/vro3', params=audio_para)
        return result.content

    def make_son_folder(self):
        charactor=self.super_parameter['selected']
        single_son_folder_path=son_list[str(charactor)]
        son_folder_path=self.super_parameter['file_path']+single_son_folder_path
        if not os.path.exists(son_folder_path):
            os.mkdir(son_folder_path)
        return son_folder_path


    def ask_path(self):
        file_path=QFileDialog.getExistingDirectory()
        if file_path!='':
            self.super_parameter['file_path']=file_path+'/'

    def select_vro(self,num):
        self.super_parameter['selected']=num
        # print(self.super_parameter['selected'])

    def processtrigger(self, q):
        '''get menu status'''
        about_status = q.text()
        # print(about_status)
        if (about_status == "Author"):
            QMessageBox.information(self, 'Author', 'Author:Masaikk')
        elif (about_status == 'Quit'):
            qApp = QApplication.instance()
            # quit
            qApp.quit()
        elif (about_status == "Set"):
            # QMessageBox.warning(self, '...', 'no more setting')
            self.combox_color=ComboxColor()
            self.combox_color.show()
            print(self.combox_color.selected_color)
            QMessageBox.warning(self, '...', '你设置了颜色也没用')
            ## BUG


if __name__ == '__main__':
    app = QApplication(sys.argv)
    myshow = Vro3()
    myshow.show()
    sys.exit(app.exec_())
